﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Validation;
using JXT.PrimaryKey.Batman.Collections;
using JXT.PrimaryKey.Batman.Domain.Models;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Specifications;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Models;
using JXT.PrimaryKey.Batman.Domain.UserSystem.Repositories;

namespace JXT.PrimaryKey.Batman.Domain.UserSystem.Services.Default
{
    public class RoleService : CachedServiceBase<Role>, IRoleService
    {
        private static readonly string _cacheKey = "list";

        public void Save(Role entity)
        {
            var result = Validator.Validate(entity);
            if (!result.IsValid)
                throw new ValidationException("entity validate error!", result.Errors);
            if (entity.Id > 0)
                LoadRepository<IRoleRepository>().Update(entity);
            else
                LoadRepository<IRoleRepository>().Add(entity);
            ClearCache();
        }

        public void Delete(Role entity)
        {
            LoadRepository<IRoleRepository>().Delete(entity.Id);
            ClearCache();
        }

        public IEnumerable<Role> GetList()
        {
            var list = Cache.Get(CacheSpace, _cacheKey) as IEnumerable<Role>;
            if (list == null)
            {
                list = LoadRepository<IRoleRepository>().GetList(null);
                foreach (var item in list)
                {
                    LoadService<IAuthorityTemplateService>().FillAuthorityEnumerable(item.Authorities);
                }
                Cache.Add(CacheSpace, _cacheKey, list);
            }
            return list;
        }
    }
}
